package com.hbnu.system.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义反序列化器，用于处理字符串或数组类型字段
 * 当输入为字符串时，直接返回字符串
 * 当输入为数组时，将数组元素用逗号分隔拼接成字符串
 */
public class StringOrArrayToCommaStringDeserializer extends JsonDeserializer<String> {
    @Override
    public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
        JsonNode node = mapper.readTree(jsonParser);
        
        // 如果是null或空值，返回空字符串
        if (node == null || node.isNull() || node.isMissingNode()) {
            return "";
        }
        
        // 如果是字符串类型，直接返回
        if (node.isTextual()) {
            String text = node.asText();
            return text != null ? text : "";
        }
        
        // 如果是数组类型，将数组元素用逗号分隔拼接成字符串
        if (node.isArray()) {
            List<String> elements = new ArrayList<>();
            for (JsonNode element : node) {
                if (element != null && !element.isNull()) {
                    elements.add(element.asText());
                }
            }
            return String.join(",", elements);
        }
        
        // 其他情况返回空字符串
        return "";
    }
}